package cn.edu.scau.cmi.chenjiale.comprehension;

import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.edu.scau.cmi.chenjiale.comprehension.entity.Student;
import cn.edu.scau.cmi.chenjiale.comprehension.entity.Teacher;
import cn.edu.scau.cmi.chenjiale.comprehension.service.StudentService;
import cn.edu.scau.cmi.chenjiale.comprehension.service.TeacherService;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

/**
 * 主启动类
 * 
 * @author chen.jiale
 * @date 2019/05/07
 *
 */
public class ManagerApplication extends Application {
	private static final Logger logger = LoggerFactory.getLogger(ManagerApplication.class);

	private TeacherService teacherService;

	private StudentService studentService;

	@Override
	public void start(Stage primaryStage) throws Exception {
		teacherService = new TeacherService();
		studentService = new StudentService();

		TabPane tabPane = new TabPane();

		// 创建两个标签，放入标签面板
		Tab stuTab = new Tab("学生");
		Tab teaTab = new Tab("教师");

		// 加载学生面板
		BorderPane stuPane = this.getStuPane(primaryStage);
		// 加载教师面板
		BorderPane teaPane = this.getTeaPane(primaryStage);

		stuTab.setContent(stuPane);
		teaTab.setContent(teaPane);
		tabPane.getTabs().addAll(stuTab, teaTab);

		primaryStage.setScene(new Scene(tabPane, 800, 400));
		primaryStage.show();

	}

	/**
	 * 加载教师数据与操作面板
	 * 
	 * @param primaryStage
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private BorderPane getTeaPane(Stage primaryStage) {
		BorderPane pane = new BorderPane();
		GridPane teaPane = new GridPane();
		teaPane.setHgap(5);
		teaPane.setVgap(5);
		List<Teacher> teacherList = teacherService.findAll();
		List<Student> studentList = studentService.findAll();
		for (int i = 0; i < teacherList.size(); i++) {
			Teacher teacher = teacherList.get(i);
			teaPane.add(new Label("工号："), 0, i);
			TextField idField = new TextField(teacher.getId() + "");
			idField.setEditable(false);
			teaPane.add(idField, 1, i);

			teaPane.add(new Label("姓名："), 2, i);
			TextField nameField = new TextField(teacher.getName());
			teaPane.add(nameField, 3, i);

			teaPane.add(new Label("学生："), 4, i);

			teaPane.add(new Label("  "), 6, i);
			Button updateBtn = new Button("修改");
			teaPane.add(updateBtn, 7, i);
			teaPane.add(new Label("  "), 8, i);
			Button deleteBtn = new Button("删除");
			teaPane.add(deleteBtn, 9, i);

			// 更新
			updateBtn.setOnAction(e -> {
				teacher.setName(nameField.getText());

				teacherService.update(teacher);
				try {
					this.start(primaryStage);
				} catch (Exception e1) {
					logger.error("更新教师失败", e1);
				}
			});

			// 删除
			deleteBtn.setOnAction(e -> {
				// 将该老师指导的所有学生的老师选项设为null
				Set<Student> students = teacher.getStudents();
				for (Student stu : students) {
					stu.setTeacher(null);
					studentService.update(stu);
				}
				teacherService.delete(teacher);
				try {
					this.start(primaryStage);
				} catch (Exception e1) {
					logger.error("删除教师失败", e1);
				}
			});
		}

		// 添加新的学生
		GridPane addPane = new GridPane();
		addPane.setHgap(5);
		Label addIdLabel = new Label("工号：");
		TextField addIdField = new TextField();
		Label addNameLabel = new Label("姓名：");
		TextField addNameField = new TextField();

		Button addBtn = new Button("新增");
		addPane.addRow(0, addIdLabel, addIdField, addNameLabel, addNameField, addBtn);

		addBtn.setOnAction(e -> {
			Teacher newTeacher = new Teacher();
			newTeacher.setName(addNameField.getText());
			teacherService.add(newTeacher);
			try {
				this.start(primaryStage);
			} catch (Exception e1) {
				logger.error("添加教师失败", e1);
			}
		});
		pane.setCenter(teaPane);
		pane.setBottom(addPane);
		return pane;
	}

	/**
	 * 获取学生数据展示与操作面板
	 * 
	 * @param primaryStage
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private BorderPane getStuPane(Stage primaryStage) {
		BorderPane pane = new BorderPane();
		GridPane stuPane = new GridPane();
		stuPane.setHgap(5);
		stuPane.setVgap(5);
		List<Student> studentList = studentService.findAll();
		List<Teacher> teacherList = teacherService.findAll();
		for (int i = 0; i < studentList.size(); i++) {
			Student student = (Student) studentList.get(i);
			Teacher teacher = student.getTeacher();

			stuPane.add(new Label("学号："), 0, i);
			TextField idField = new TextField(student.getId() + "");
			idField.setEditable(false);
			stuPane.add(idField, 1, i);

			stuPane.add(new Label("姓名："), 2, i);
			TextField nameField = new TextField(student.getName());
			stuPane.add(nameField, 3, i);

			stuPane.add(new Label("导师："), 4, i);
			ComboBox<String> combo = this.getCommboBox(teacherList);
			if (null != teacher) {
				combo.setValue(teacher.getName());
			}
			stuPane.add(combo, 5, i);
			stuPane.add(new Label("  "), 6, i);
			Button updateBtn = new Button("修改");
			stuPane.add(updateBtn, 7, i);
			stuPane.add(new Label("  "), 8, i);
			Button deleteBtn = new Button("删除");
			stuPane.add(deleteBtn, 9, i);

			// 更新
			updateBtn.setOnAction(e -> {
				student.setName(nameField.getText());
				String teacherName = combo.getValue();
				if (null != teacherName && !teacherName.equals("")) {
					for (Teacher tutor : teacherList) {
						if (teacherName.equals(tutor.getName())) {
							student.setTeacher(tutor);
							break;
						}
					}
				}
				studentService.update(student);
				try {
					this.start(primaryStage);
				} catch (Exception e1) {
					logger.error("更新学生失败", e1);
				}
			});

			// 删除
			deleteBtn.setOnAction(e -> {
				studentService.delete(student);
				try {
					this.start(primaryStage);
				} catch (Exception e1) {
					logger.error("删除学生失败", e1);
				}
			});
		}

		// 添加新的学生
		GridPane addPane = new GridPane();
		addPane.setHgap(5);
		Label addIdLabel = new Label("学号：");
		TextField addIdField = new TextField();
		Label addNameLabel = new Label("姓名：");
		TextField addNameField = new TextField();
		Label addTeacherLabel = new Label("指导教师：");

		ComboBox<String> combo = this.getCommboBox(teacherList);
		Button addBtn = new Button("新增");
		addPane.addRow(0, addIdLabel, addIdField, addNameLabel, addNameField, addTeacherLabel, combo, addBtn);

		addBtn.setOnAction(e -> {
			Student student = new Student();
			student.setId(Long.parseLong(addIdField.getText()));
			student.setName(addNameField.getText());
			String teacherName = combo.getValue();
			for (Teacher teacher : teacherList) {
				if (teacherName.equals(teacher.getName())) {
					student.setTeacher(teacher);
					break;
				}
			}
			studentService.add(student);
			try {
				this.start(primaryStage);
			} catch (Exception e1) {
				logger.error("添加学生失败", e1);
			}
		});
		pane.setCenter(stuPane);
		pane.setBottom(addPane);

		return pane;
	}

	/**
	 * 获取教师列表组合框
	 * 
	 * @return
	 */
	private ComboBox<String> getCommboBox(List<Teacher> teacherList) {
		ComboBox<String> combo = new ComboBox<String>();
		for (Teacher teacher : teacherList) {
			combo.getItems().add(teacher.getName());
		}
		return combo;
	}

	public static void main(String[] args) {
		Application.launch(args);
	}

}
